import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/app_fonts.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/custom_button_widget.dart';
import 'package:leader_doctor_flutter/common/widget/refresh_custom_widget.dart';
import 'package:leader_doctor_flutter/common/widget/table_placeholder_widget.dart';
import 'package:leader_doctor_flutter/model/my_doctor_service_refund_application_model.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:leader_doctor_flutter/ui/mine/page/event/refresh_event.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyDoctorServiceRefundApplicationPage extends StatefulWidget {
  const MyDoctorServiceRefundApplicationPage({super.key});

  @override
  State<MyDoctorServiceRefundApplicationPage> createState() =>
      _MyDoctorServiceRefundApplicationPageState();
}

class _MyDoctorServiceRefundApplicationPageState
    extends State<MyDoctorServiceRefundApplicationPage> {
  var pageSize = 20;
  var pageNo = 1;
  bool dataLoaded = false; // 数据请求中

  List<MyDoctorServiceRefundApplicationListModel> dataArray = [];

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    pageNo = 1;
    // _getRefundApplicationList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    pageNo++;
    // _getRefundApplicationList();
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();

    App.instance.eventBus.on<RefreshEvent>().listen((event) {
      pageNo = 1;
      _getRefundApplicationList();
      print("申请退款接收到了发的通知");
    });

    _getRefundApplicationList();
  }

  @override
  Widget build(BuildContext context) {
    return contentView();
  }

  Widget contentView() {
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context),
      body: Container(
        color: Color(0xFFF5F7F9),
        width: double.infinity,
        height: double.infinity,
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.only(
                  right: 12.w, left: 12.w, top: 12.w, bottom: 12.w),
              color: ColorRes.colore6e6ff,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                    padding: EdgeInsets.only(top: 2.w),
                    child: ImageLoader.loadAsset("icon_cp_alert.png", 15.w,color: ColorRes.colorMain),
                  ),
                  SizedBox(
                    width: 5.w,
                  ),
                  Expanded(
                    child: Text(
                      "若医生七天内还未为患者处理退款，系统将会自动为其退款",
                      style: TextStyle(
                        fontSize: 13.sp,
                        color: ColorRes.color333333,
                        fontFamily: AppFonts.pingFangSC,
                        fontWeight: AppFonts.medium,
                      ),
                    ),
                  )
                ],
              ),
            ),
            Expanded(
              child: Container(
                child: SmartRefresher(
                  controller: _refreshController,
                  enablePullDown: true,
                  enablePullUp: true,
                  onRefresh: _onRefresh,
                  onLoading: _onLoading,
                  header: RefreshCustomHeaderWidget(),
                  footer: RefreshCustomFooterWidget(),
                  child: dataLoaded
                      ? dataArray.isEmpty
                          ? TablePlaceholderWidget(
                              message: "暂无数据",
                              yOffset: -30,
                            )
                          : ListView.builder(
                              itemCount: dataArray.length,
                              itemBuilder: (BuildContext context, int index) {
                                return Column(
                                  children: [
                                    SizedBox(height: 10.w),
                                    _buildListItem(dataArray[index]),
                                  ],
                                );
                              },
                            )
                      : Container(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取申请退款列表
  _getRefundApplicationList() async {
    var user = App.instance.userInfo;
    var httpRequest = HttpRequest(Api.refundApplicationList, body: {
      'doctorId': user?.id,
      "pageIndex": pageNo.toString(),
      "pageSize": pageSize.toString()
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var serviceResult =
        ServiceResult<List<MyDoctorServiceRefundApplicationListModel>>.list(
            httpResponse,
            (map) => (map ?? [])
                .map((e) =>
                    MyDoctorServiceRefundApplicationListModel.fromJson(e))
                .toList());
    if (serviceResult.success) {
      var list = serviceResult.responseBody ?? [];
      print("申请退款列表：${list.toString()}");
      if (pageNo == 1) {
        dataArray.clear();
      }
      dataArray.addAll(list);

      if (list.length < pageSize) {
        _refreshController.loadNoData();
      } else {
        _refreshController.loadComplete();
      }
    }
    setState(() {
      dataLoaded = true;
    });
  }

  Widget _buildListItem(MyDoctorServiceRefundApplicationListModel model) {
    var user = App.instance.userInfo;
    String patientNameStr = model.patientName ?? "";
    String sexStr = model.sex ?? "";
    String ageStr = model.age ?? "";
    sexStr = sexStr == "1" ? "男" : "女";
    String ageAndSex = sexStr + " | " + ageStr + "岁";
    // 订单来源医生
    String orderSourceDoctor = model.orderSource ?? "";
    // 医生姓名
    String doctorName = model.doctorName ?? "";
    // 所有医生Id
    String belongDoctorId = model.doctorId ?? "";
    // 所有医生
    String belongDoctor = "";
    if (belongDoctorId != user?.id) {
      belongDoctor = doctorName;
    }
    // 订单来源
    String orderSource = model.orderSource ?? "";

    // 购买时间
    String purchaseTime = model.purchaseTime ?? "";
    int servicePrice = model.price ?? 0;
    String servicePriceStr = (servicePrice / 100).toStringAsFixed(2);

// 第三行标题
    String thirdLineTitleStr = "";
    // 第三行描述
    String thirdLineDescStr = "";
    // 第三行标题颜色
    Color thirdLineTitleColor = ColorRes.color9A9A9A;
    // 第三行描述颜色
    Color thirdLineDescColor = ColorRes.color333333;

    // 第四行标题
    String fourLineTitleStr = "";
    // 第四行描述
    String fourLineDescStr = "";
    // 第四行标题颜色
    Color fourLineTitleColor = ColorRes.color9A9A9A;
    // 第四行描述颜色
    Color fourLineDescColor = ColorRes.color333333;

    // 第五行标题
    String fiveLineTitleStr = "";
    // 第五行描述
    String fiveLineDescStr = "";
    // 第五行标题颜色
    Color fiveLineTitleColor = ColorRes.color9A9A9A;
    // 第五行描述颜色
    Color fiveLineDescColor = ColorRes.color333333;

    // 订单使用状态
    String status = model.status ?? "";

    Color statusColor = ColorRes.color666666;
    String statusStr = "";
    if (status == "untreated") {
      // 未使用
      statusStr = "未使用";
      statusColor = ColorRes.color666666;
    } else if (status == "finish") {
      // 已使用
      statusStr = "已使用";
      statusColor = Color(0xFF2AA515);
    } else if (status == "refund") {
      // 已退款
      statusStr = "已退款";
      statusColor = ColorRes.color666666;
    }

    // 订单是否有来源，没有则不显示
    if (orderSource.isEmpty) {
      // 没有来源
      fourLineTitleStr = "订单状态：";
      fourLineDescStr = "申请退款中";
      fourLineTitleColor = ColorRes.color9A9A9A;
      fourLineDescColor = ColorRes.color333333;
    } else {
      // 有来源
      fourLineTitleStr = "订单来源：";
      fourLineDescStr = orderSource;
      fourLineTitleColor = ColorRes.color9A9A9A;
      fourLineDescColor = ColorRes.color333333;
      fiveLineTitleStr = "订单状态：";
      fiveLineDescStr = "申请退款中";
      fiveLineTitleColor = ColorRes.color9A9A9A;
      fiveLineDescColor = ColorRes.color333333;
    }

    return GestureDetector(
      behavior: HitTestBehavior.opaque, // 点击空白处也可以响应
      onTap: () => _jumpDetail(model),
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: 12.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.w),
        ),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.only(
                  top: 12.w, bottom: 12.w, right: 12.w, left: 12.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  RichText(
                    text: TextSpan(children: [
                      TextSpan(
                        text: "${patientNameStr}",
                        style: TextStyle(
                          color: ColorRes.color333333,
                          fontSize: 15.sp,
                          fontFamily: AppFonts.pingFangSC,
                          fontWeight: AppFonts.bold,
                        ),
                      ),
                      WidgetSpan(
                        child: SizedBox(
                          width: 20.w,
                        ),
                      ),
                      TextSpan(
                        text: "${ageAndSex}",
                        style: TextStyle(
                          color: ColorRes.color666666,
                          fontSize: 15.sp,
                          fontFamily: AppFonts.pingFangSC,
                          fontWeight: AppFonts.medium,
                        ),
                      ),
                    ]),
                  ),
                  ImageLoader.loadAsset("icon_refund_unused.webp", 44.w),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.only(right: 12.w, left: 12.w),
              child: SizedBox(
                height: 1.w,
                child: Container(color: Color(0xFFF2F2F2)),
              ),
            ),
            Container(
              padding: EdgeInsets.only(
                  top: 12.w, bottom: 12.w, right: 12.w, left: 12.w),
              width: double.infinity,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Container(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        RichText(
                          text: TextSpan(children: [
                            TextSpan(
                              text: "服务名称：",
                              style: TextStyle(
                                color: ColorRes.color9A9A9A,
                                fontSize: 14.sp,
                                fontFamily: AppFonts.pingFangSC,
                                fontWeight: AppFonts.medium,
                              ),
                            ),
                            TextSpan(
                              text: "${model.title}",
                              style: TextStyle(
                                color: ColorRes.color333333,
                                fontSize: 14.sp,
                                fontFamily: AppFonts.pingFangSC,
                                fontWeight: AppFonts.medium,
                              ),
                            ),
                          ]),
                        ),
                        SizedBox(
                          height: 3.w,
                        ),
                        RichText(
                          text: TextSpan(children: [
                            TextSpan(
                              text: "服务价格：",
                              style: TextStyle(
                                color: ColorRes.color9A9A9A,
                                fontSize: 14.sp,
                                fontFamily: AppFonts.pingFangSC,
                                fontWeight: AppFonts.medium,
                              ),
                            ),
                            TextSpan(
                              text: "${servicePriceStr}元",
                              style: TextStyle(
                                color: ColorRes.color333333,
                                fontSize: 14.sp,
                                fontFamily: AppFonts.pingFangSC,
                                fontWeight: AppFonts.medium,
                              ),
                            ),
                          ]),
                        ),
                        SizedBox(
                          height: 3.w,
                        ),
                        RichText(
                          text: TextSpan(children: [
                            TextSpan(
                              text: "购买时间：",
                              style: TextStyle(
                                color: thirdLineTitleColor,
                                fontSize: 14.sp,
                                fontFamily: AppFonts.pingFangSC,
                                fontWeight: AppFonts.medium,
                              ),
                            ),
                            TextSpan(
                              text: "${purchaseTime}",
                              style: TextStyle(
                                color: thirdLineDescColor,
                                fontSize: 14.sp,
                                fontFamily: AppFonts.pingFangSC,
                                fontWeight: AppFonts.medium,
                              ),
                            ),
                          ]),
                        ),
                        SizedBox(
                          height: 3.w,
                        ),
                        if (fourLineTitleStr.isNotEmpty)
                          RichText(
                            text: TextSpan(children: [
                              TextSpan(
                                text: "${fourLineTitleStr}",
                                style: TextStyle(
                                  color: fourLineTitleColor,
                                  fontSize: 14.sp,
                                  fontFamily: AppFonts.pingFangSC,
                                  fontWeight: AppFonts.medium,
                                ),
                              ),
                              if (fourLineDescStr.isNotEmpty)
                                TextSpan(
                                  text: "${fourLineDescStr}",
                                  style: TextStyle(
                                    color: fourLineDescColor,
                                    fontSize: 14.sp,
                                    fontFamily: AppFonts.pingFangSC,
                                    fontWeight: AppFonts.medium,
                                  ),
                                ),
                            ]),
                          ),
                        SizedBox(
                          height: 3.w,
                        ),
                        if (fiveLineTitleStr.isNotEmpty)
                          RichText(
                            text: TextSpan(children: [
                              TextSpan(
                                text: "${fiveLineTitleStr}",
                                style: TextStyle(
                                  color: fiveLineTitleColor,
                                  fontSize: 14.sp,
                                  fontFamily: AppFonts.pingFangSC,
                                  fontWeight: AppFonts.medium,
                                ),
                              ),
                            ]),
                          ),
                        // Container(
                        // padding: EdgeInsets.only(
                        //     left: 12.w, right: 12.w, top: 50.w),
                        //   child: initBottomBtnView(),
                        // )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 调转到详情
  _jumpDetail(MyDoctorServiceRefundApplicationListModel model) async {
    print("调转到详情 = ${model.toJson()}");
    context.push(PageUrl.doctorServiceDetails + "?id=${model.purchaseId}");
  }

  // 底部拒绝、同意退款、确定完成服务按钮UI
  Widget initBottomBtnView() {
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: CustomButtonWidget(
              text: "拒绝退款",
              onTap: () {
                print("拒绝退款");
              },
              textStyle: TextStyle(
                fontSize: 14.sp,
                color: ColorRes.white,
                fontFamily: AppFonts.pingFangSC,
                fontWeight: AppFonts.medium,
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.w),
                color: Color(0xFFFF2D55), // 添加背景色
              ),
            ),
          ),
          SizedBox(
            width: 15.w,
          ),
          Expanded(
            child: CustomButtonWidget(
              text: "同意退款",
              onTap: () {
                print("同意退款");
              },
              textStyle: TextStyle(
                fontSize: 14.sp,
                color: ColorRes.white,
                fontFamily: AppFonts.pingFangSC,
                fontWeight: AppFonts.medium,
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.w),
                color: ColorRes.colorMain, // 添加背景色
              ),
            ),
          ),
          SizedBox(
            width: 15.w,
          ),
          Expanded(
            child: CustomButtonWidget(
              text: "确定完成服务",
              onTap: () {
                print("确定完成服务");
              },
              textStyle: TextStyle(
                fontSize: 14.sp,
                color: ColorRes.white,
                fontFamily: AppFonts.pingFangSC,
                fontWeight: AppFonts.medium,
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.w),
                color: ColorRes.colorMain, // 添加背景色
              ),
            ),
          ),
        ],
      ),
    );
  }
}
